/** @format */

// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const uuid = require('uuid');
const dayjs = require('dayjs');
module.exports = {
	_before: function() {
		// 通用预处理器
	},
	/* 新增任务列表*/
	async add(event) {
		const {
			params,
			openId
		} = event;
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo(),
		});
		let res
		if (params._id) {
			const res = await updateTaskList(dbJQL, openId, params);
		} else {
			res = await saveTaskList(dbJQL, openId, params);
		}
		return {
			code: 0,
			msg: '',
			data: {},
		};
	},
	// 修改任务列表
	async updateList(event) {
		const {
			params,
			openId
		} = event;
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo(),
		});
		const res = await updateTaskList(dbJQL, openId, params);
		return {
			code: 0,
			msg: '',
			data: {},
		};
	},
	/* 查询任务列表*/
	async getList(event) {
		// 获取JQL database引用，此处需要传入云对象的clientInfo
		console.log('getList', event);
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo(),
		});
		const res = await fetchSortedData(dbJQL, event);
		console.log('111', res);
		return {
			code: 0,
			msg: '',
			data: res.data,
		};
	},
	async getTaskDetail(event) {
		console.log('getTaskInfo', event);
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo(),
		});
		const res = await fetchTaskDetail(dbJQL, event);
		console.log('111', res);
		return {
			code: 0,
			msg: '',
			data: res.data,
		};
	}
};
//
function fetchSortedData(db, params) {
	const {
		taskType = '1', taskPriority, OPENID, taskRepeat, taskTiming, openid
	} = params;
	const todayStartDateNow = dayjs().startOf('day').valueOf();
	const todayEndDateNow = dayjs().startOf('day').add(1, 'days').subtract(1, 'milliseconds').valueOf();
	const query = {
		creator: `creator == '${openid}'`,
		taskType: `taskType == '${taskType}'`,
		taskRepeat: `taskRepeat == '1'`,
		delFlag: `delFlag == '0'`,
		status: `(status == '1' || (status in ['0','2','3'] && startTime >= ${todayStartDateNow} && startTime <= ${todayEndDateNow}))`,
	};
	//  status  0-未开始 1-进行中 2-已完成 3-未完成
	if (taskPriority) {
		query.taskPriority = `taskPriority == ${taskPriority}`;
	}
	// 如果是查询重复任务，则不查询时间
	if (taskRepeat) {
		query.taskRepeat = `taskRepeat != '1'`;
		query.status = `status == '0' `; // 移除时间条件，避免冲突
	}
	//  查询定时任务
	if (taskTiming) {
		query.status = `status == '0'`;
		query.startTime = `startTime >= ${todayEndDateNow}`;
	}
	let sql = '';
	Object.keys(query).forEach((key) => {
		const ql = query[key];
		sql += ' && ' + ql;
	});
	if (sql) {
		sql = sql.replace(' && ', '');
		sql = `"${sql}"`;
	}
	console.log('我要打印的值:sql', sql);
	const list = db.collection('task_list').where(sql).orderBy('finishTime startTime asc').getTemp();
	const subList = db.collection('task_sub_list').where("delFlag == '0'").orderBy('finishTime asc').getTemp();
	return db.collection(list, subList).field(
		'tid.task_sub_list as taskSubList,tid._value as taskId,startTime,endTime,status,taskType,taskPriority,taskRepeat,label'
	).get();
}
//
function saveTaskList(dbJQL, openId, params) {
	const taskId = uuid.v4();
	const subTaskList = params.taskSubList;
	delete params.taskSubList;
	const timeNow = Date.now();
	return Promise.all([
		dbJQL.collection('task_list').add({
			tid: taskId,
			//   任务描述
			...params,
			startTimeDes: dayjs(params.startTime).format('YYYY-MM-DD HH:mm:ss'),
			//   创建人
			creator: openId,
			//   创建时间
			createTime: timeNow,
			//   完成时间
			finishTime: 0,
			//   更新时间
			updateTime: '',
			//   开始状态
			status: '0',
			//   删除状态
			delFlag: '0',
		}),
		dbJQL.collection('task_sub_list').add(
			subTaskList.map((item) => ({
				taskId,
				createTime: timeNow,
				updateTime: '',
				finishTime: 0,
				content: item.content,
				delFlag: '0',
				status: '0',
			}))
		),
	]);
}
//
function updateTaskList(dbJQL, openId, params) {
	const {
		tid,
		taskSubList
	} = params;
	const task_sub_list = taskSubList;
	delete params.taskSubList;
	delete params.taskId;
	delete params.edit;
	delete params.collapseValue
	const isAllSuccess = taskSubList.every(item => item.status == '1')
	const timeNow = Date.now();
	if (isAllSuccess) {
		params.finishTime = timeNow
		params.status = '2'
	}
	dbJQL.collection('task_list').doc(tid).update(params);
	for (const item of task_sub_list) {
		delete item.edit;
		if (item.status == 1) {
			item.finishTime = timeNow
		}
		dbJQL.collection('task_sub_list').doc(item._id).update(item);
	}
}

function fetchTaskDetail(db, event) {
	const {
		openId,
		id
	} = event
	const list = db.collection('task_list').where(`"creator == '${openId}' && _id == '${id}' && delFlag == '0'"`)
		.orderBy('finishTime startTime asc').getTemp();
	const subList = db.collection('task_sub_list').where("delFlag == '0'").orderBy('finishTime asc').getTemp();
	return db.collection(list, subList).field(
		'tid.task_sub_list as taskSubList,tid._value as taskId,startTime,endTime,status,taskType,taskPriority,taskRepeat,label'
	).get();
}